class AntennasController < ApplicationController
  before_action :set_antenna, only: [:show, :edit, :update]
  skip_before_filter :verify_authenticity_token, :only => [:order]

  def index
    @antennas = Antenna.all.order(:ordenation)
  end

  def show
  end

  def new
    @readers = Reader.all
    @antenna = Antenna.new
  end

  def edit
    @readers = Reader.all
  end

  def create
    @readers = Reader.all
    @antenna = Antenna.new(antenna_params)
    @antenna.ordenation = Antenna.first.nil? ? 1 : Antenna.order(:ordenation).last.ordenation + 1
    respond_to do |format|
      if @antenna.save
        format.html { redirect_to antennas_path, notice: 'Antenna was successfully created.' }
        format.json { render action: 'show', status: :created, location: @antenna }
      else
        format.html { render action: 'new' }
        format.json { render json: @antenna.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @antenna.update(antenna_params)
        format.html { redirect_to antennas_path, notice: 'Antenna was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @antenna.errors, status: :unprocessable_entity }
      end
    end
  end


  def destroy
    @antenna = Antenna.find(params[:antenna_id])
    @antenna.destroy
    respond_to do |format|
      format.html { redirect_to antennas_url }
      format.json { head :no_content }
    end
  end
  
  def order
    order = params[:orders]
    orderPointer = 0
    
    Antenna.all.order(:ordenation).each do |antenna|
      antenna.ordenation = order[orderPointer]
      orderPointer = orderPointer + 1
      antenna.save
    end 
    
    respond_to do |format|
      format.html { "ok" }
      format.json { head :no_content }
    end
  end

  private
    def set_antenna
      @antenna = Antenna.find(params[:id])
    end

    def antenna_params
      params.fetch(:antenna, {}).permit(:description, :reader_id, :tx_rx_port, :power, :protocol)
    end
end
